/// <reference types="vite/client" />
import { ConfigEnv, defineConfig, loadEnv, UserConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import { resolve } from 'path'
import AutoImport from 'unplugin-auto-import/vite'
import Components from 'unplugin-vue-components/vite'
import { ElementPlusResolver } from 'unplugin-vue-components/resolvers'
import ElementPlus from 'unplugin-element-plus/vite'
import UnoCSS from 'unocss/vite'
import EslintPlugin from 'vite-plugin-eslint'
import { ViteEjsPlugin } from 'vite-plugin-ejs'
import pxToVp from 'postcss-px-to-viewport'
import pxToVpConfig from './postcss.config'
import Pages from 'vite-plugin-pages'
import Layouts from 'vite-plugin-vue-layouts'

const root = process.cwd()

// https://vite.dev/config/
export default defineConfig(({ command, mode }: ConfigEnv): UserConfig => {
  let env: ImportMetaEnv
  const isBuild = command === 'build'
  if (!isBuild) {
    env = loadEnv(process.argv[3] === '--mode' ? process.argv[4] : process.argv[3], root) as unknown as ImportMetaEnv
  } else {
    env = loadEnv(mode, root) as unknown as ImportMetaEnv
  }

  return {
    plugins: [
      vue(),
      Pages({
        dirs: 'src/views', // 指定页面目录（默认值）
        extensions: ['vue', 'ts', 'tsx'], // 支持的文件扩展名
        exclude: ['**/components/**'] // 排除的目录
      }),
      Layouts({
        layoutsDirs: 'src/layouts',
        defaultLayout: 'Default'
      }),
      UnoCSS(),
      Components({
        resolvers: [ElementPlusResolver()],
        dirs: ['src/components']
      }),
      AutoImport({
        imports: ['vue', 'vue-router', 'pinia'],
        resolvers: [ElementPlusResolver()],
        eslintrc: { enabled: true }
      }),
      EslintPlugin({
        cache: false,
        failOnWarning: false,
        failOnError: false,
        include: ['src/**/*.vue', 'src/**/*.ts', 'src/**/*.tsx'] // 检查的文件
      }),
      ViteEjsPlugin({
        title: env.VITE_APP_TITLE
      }),
      ElementPlus()
    ],
    base: './',
    resolve: {
      alias: [{ find: '@', replacement: resolve(__dirname, 'src') }]
    },
    server: {
      host: '0.0.0.0',
      open: true,
      proxy: {
        '/api': {
          target: `http://127.0.0.1/api`, // 后端接口前缀
          changeOrigin: true, // 是否允许跨域
          secure: false, // 如果是https接口，需要配置这个参数
          rewrite: (path) => path.replace(/^\/api/, '')
        }
      }
    },
    css: {
      postcss: {
        plugins: [pxToVp(pxToVpConfig)]
      }
    }
  }
})
